//
//  ChooseGiftViewController.m
//  GiftNote
//
//  Created by wsh on 15/8/19.
//  Copyright (c) 2015年 GN. All rights reserved.
//

#import "ChooseGiftViewController.h"
#import "DorpDownListView.h"
#import "Screen.h"
#import "ArtifactCollectionViewCell.h"
#import "ArtifactModel.h"
#import "INHeader.h"
#import "LORequestManger.h"
#import "PKRequestManager.h"
#import "MJRefresh.h"
#import "ChooseGiftModel.h"
#import "HomeMenueView.h"

//  用判断刷新的方式(是下拉刷新还是上拉加载)
typedef NS_ENUM(NSInteger, RefreashType){
    RefreashTypeNew,  //  下拉刷新
    RefreashTypeMore     //  上拉加载
};



//上拉时解析的数据

#define ArtifactUrl @"http://api.liwushuo.com/v2/search/item_by_type?limit=20&offset=%ld"
@interface ChooseGiftViewController () <UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,DorpDownChooseDelegate,DorpDownChooseDataSource,HomeMenuDelegate>

@property(nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) NSInteger num;  // 每次加载的数据个数
@property (nonatomic, assign) RefreashType refreashType; //  刷新的方式

@property(nonatomic, strong) DorpDownListView *listView;
@property (nonatomic, strong) HomeMenueView *menu;


@property (nonatomic, assign) NSInteger index;  //  选择的排序下表序号

@property(nonatomic, strong) NSMutableArray *artifactArray;  //  下面collectionView的数组
@property(nonatomic, strong) NSMutableArray *chooseArray;    //  展示在选择横条的数组

@property (nonatomic, strong) NSString *currentUrl;   //  当前的解析网址
@property (nonatomic, strong) NSString *urlString;           // collectionView解析需要的网址

@property (nonatomic, strong) NSString *targetUrl;           //  对象的字符串
@property (nonatomic, strong) NSString *sceneUrl;            //  场合的字符串
@property (nonatomic, strong) NSString *personalityUrl;      //  个性的字符串
@property (nonatomic, strong) NSString *priceUrl;            //  价格的字符串
@property (nonatomic, strong) NSString *lastPriceGroupId;        //  保存上一次选中的价格的GroupId
@end



@implementation ChooseGiftViewController
#pragma mark --- 懒加载
- (NSMutableArray * )artifactArray{
    
    if (!_artifactArray) {
        self.artifactArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _artifactArray;
}

- (NSMutableArray *)chooseArray{
    if (!_chooseArray) {
        self.chooseArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _chooseArray;
}


- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = YES;
    [self.menu menuDismiss];
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"选礼神器";
    
    //  改变返回按钮的颜色
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    self.view.backgroundColor = [UIColor whiteColor];

    //创建布局对象 这个对象专门控制我们集合视图的布局
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //创建 UICollectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT - 49 - 40) collectionViewLayout:flowLayout];
    
    [self.collectionView registerClass:[ArtifactCollectionViewCell class] forCellWithReuseIdentifier:@"cellArtical"];
    
    
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:_collectionView];
    
    //设置集合视图的颜色 默认是黑色的
    self.collectionView.backgroundColor = [UIColor colorWithRed:220/256.0 green:240/256.0 blue:240/256.0 alpha:0.8];
    
    
    //  设置一开始加载的数据个数以及调用刷新函数
    _num = 0;
    [self refreashData];
    _index = 0;
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-paixu"] style:UIBarButtonItemStylePlain target:self action:@selector(sortAction)];
    
    NSArray *array = @[@"默认排序", @"按热度排序", @"价格从低到高", @"价格从高到低"];
    _menu = [[HomeMenueView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 160, 64, 150, 176) array:array];
    _menu.delegate = self;
    _menu.layer.masksToBounds = YES;
    
    _menu.layer.cornerRadius = 25;
    
    _urlString = ArtifactUrl;


    [self artifactRequest];
    [self readData];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(changUrl:) name:@"检测button的名字" object:nil];
}


- (void)changUrl:(NSNotification *)notifi{
    
    NSIndexPath *indexPath = notifi.object;
    ChooseGiftModel *model = _chooseArray[indexPath.section];
    
    NSString *group_id = model.channels[indexPath.item][@"group_id"];

    switch (indexPath.section) {
        case 0:
        {
            if ([self hasThisString:@"&target="]) {
                [self delegateString:@"&target="];
            }
            if (![group_id isEqualToString:@"0"]) {
                _targetUrl = [NSString stringWithFormat:@"&target=%@",group_id];
                _urlString = [NSString stringWithFormat:@"%@%@",_urlString,_targetUrl];
            }
        }
            break;
        case 1:
        {
            if ([self hasThisString:@"&scene="]) {
                [self delegateString:@"&scene="];

            }
            if (![group_id isEqualToString:@"0"]) {
                _sceneUrl = [NSString stringWithFormat:@"&scene=%@",group_id];
                _urlString = [NSString stringWithFormat:@"%@%@",_urlString,_sceneUrl];
            }
        }
            break;
        case 2:
        {
            if ([self hasThisString:@"&personality="]) {
                [self delegateString:@"&personality="];

            }
            if (![group_id isEqualToString:@"0"]) {
                _personalityUrl = [NSString stringWithFormat:@"&personality=%@",group_id];
                _urlString = [NSString stringWithFormat:@"%@%@",_urlString,_personalityUrl];
            }
        }
            break;
        case 3:
        {
            if ([self hasThisString:@"&price="]) {
                [self delegateString2:[NSString stringWithFormat:@"&price=%@",_lastPriceGroupId]];
            }
            if (![group_id isEqualToString:@"0"]) {
                _priceUrl = [NSString stringWithFormat:@"&price=%@",group_id];
                _urlString = [NSString stringWithFormat:@"%@%@",_urlString,_priceUrl];
            }
            _lastPriceGroupId = group_id;

        }
            break;
        default:
            break;
    }

    [self readData];
    [self.collectionView.gifHeader beginRefreshing];
}


//  判断在网址里有么有这个字符串
- (BOOL)hasThisString:(NSString *)str{

    if ([_urlString containsString:str]) {
        return YES;
    } else {
        return NO;
    }
}

//  在网址里删除指定的字符串
- (void)delegateString:(NSString *)str{
    
    NSRange rang = [_urlString rangeOfString:str];
    NSString *str1 = [_urlString substringToIndex:rang.location ];
    NSString *str2 = [_urlString substringFromIndex:rang.length + rang.location + 2];
    _urlString = [NSString stringWithFormat:@"%@%@",str1,str2];
}

//  在网址里删除指定的字符串
- (void)delegateString2:(NSString *)str{
    
    NSRange rang = [_urlString rangeOfString:str];
    NSString *str1 = [_urlString substringToIndex:rang.location ];
    NSString *str2 = [_urlString substringFromIndex:rang.length + rang.location ];
    _urlString = [NSString stringWithFormat:@"%@%@",str1,str2];
}



#pragma mark - DorpDownChooseDelegate
// 点击了哪个位置的标题的下拉菜单的哪个Item
- (void)chooseAtSection:(NSInteger)section index:(NSInteger)index{
    
//    ChooseGiftModel *model = self.chooseArray[section];
//    NSLog(@"%@",model.channels[index][@"name"]);
}

#pragma mark - DorpDownChooseDataSource
// 展示标题section的个数
- (NSInteger)numberofSection{
    
    return self.chooseArray.count;
}


// 每个标题的下拉菜单有多少个数据
- (NSInteger)numberofRowsInSection:(NSInteger)section{
    

    ChooseGiftModel *model = self.chooseArray[section];
    
    return model.channels.count;;
}


// 每个大标题下的小标题
- (NSString *)titleInSection:(NSInteger)section index:(NSInteger)index{

    ChooseGiftModel *model = self.chooseArray[section];
    
//    [self.listView setTitle:model.name inSection:section];
    return model.channels[index][@"name"];
}

//  第一次设置button的标题
- (NSString *)firstTitleInSection:(NSInteger)section index:(NSInteger)index{

    ChooseGiftModel *model = self.chooseArray[section];
    
    [self.listView setTitle:model.name inSection:section];
    return model.name;
}



// 默认显示的section
- (NSInteger)defaultShowSection:(NSInteger)section{
    
    return 0;
}



#pragma mark - UICollectionViewDataSource
//每个分区返回的cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.artifactArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ArtifactCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellArtical" forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor whiteColor];
    
    ArtifactModel *model = self.artifactArray[indexPath.item];
    cell.model = model;

    return cell;
}


#pragma mark - UICollectionViewDelegateFlowLayout
// 返回四个参数,是整体距离上,左,下,右的参数
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(10, 10, 10, 10);
}


//返回行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 10;
}

//返回列间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 1;
}

//返回cell的宽和高
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake((SCREEN_WIDTH - 30) / 2.0, 240 / 170.0 * (SCREEN_WIDTH - 30) / 2.0);
}



#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    // 跳转到宝贝详情页面
}


#pragma mark - 解析数据部分 (展示在View上的)
- (void)artifactRequest{
    
    //  获取数据的路径
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"gift" ofType:@"plist"];
    
    //  接收数据
    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
    
    for (NSDictionary *dic in array) {
        ChooseGiftModel *model = [[ChooseGiftModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.chooseArray addObject:model];
    }
    
    
    UIImageView *bottomView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 39, SCREEN_WIDTH, 1)];
    bottomView.backgroundColor = [UIColor lightGrayColor];
    
    self.listView = [[DorpDownListView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40) datasourse:self delegate:self];
    
    self.listView.bigSuperView = self.view;
    self.listView.backgroundColor = [UIColor colorWithRed:220/256.0 green:240/256.0 blue:240/256.0 alpha:.8];
    [self.listView addSubview:bottomView];
    
    [self.view addSubview:_listView];
}


#pragma mark - 解析数据部分 (当前collectionView上展示)
- (void)readData{
    switch (_index) {
        case 0:
            _currentUrl = [NSString stringWithFormat:_urlString,(long)_num];
            break;
        case 1:
            _currentUrl = [[NSString stringWithFormat:_urlString,(long)_num] stringByAppendingString:@"&sort=hot"];

            break;
        case 2:
            _currentUrl = [[NSString stringWithFormat:_urlString,(long)_num] stringByAppendingString:@"&sort=price%3Aasc"];

            break;
        case 3:
            _currentUrl = [[NSString stringWithFormat:_urlString,(long)_num] stringByAppendingString:@"&sort=price%3Adesc"];
            break;
        default:
            break;
    }
    
    [PKRequestManager manager:GET requestWith:_currentUrl parDic:nil finish:^(NSData *data) {

        if (data == nil) {
            return ;  
        }
        
        if (_refreashType == RefreashTypeNew) {
            [self.artifactArray removeAllObjects];
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSArray *arr = dic[@"data"][@"items"];
        for (NSDictionary *dic in arr) {
            ArtifactModel *model = [[ArtifactModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.artifactArray addObject:model];
        }
        
        [self.collectionView reloadData];
    } error:^(NSError *error) {
        
    }];
//    NSLog(@"123");
}


#pragma mark --- action
- (void)refreashData{
    
    [self.collectionView addGifHeaderWithRefreshingTarget:self refreshingAction:@selector(refeashNew)];
    [self.collectionView addGifFooterWithRefreshingTarget:self refreshingAction:@selector(refreashMore)];
}

//  刷新数据(重新开始加载)
- (void)refeashNew{
    
    _num = 0;
    _refreashType = RefreashTypeNew;
    [self readData];
    [self.collectionView.gifHeader endRefreshing];
}

//  加载数据(加载一次,增加20条数据)
- (void)refreashMore{
    
    _num += 20;
    _refreashType = RefreashTypeMore;
    [self readData];
    
    [self.collectionView.gifFooter endRefreshing];
}

- (void)sortAction{
    
    if (_menu.isShow) {
        [self.menu menuDismiss];
    } else {
        [self.menu menuShow:self.navigationController];
    }
}


//  HomeMenueView的代理方法,即根据不同的排序下表,来调用不同的数据源
- (void)transportMenuName:(NSString *)name index:(NSInteger)index{
    
    _index = index;
    [self readData];
    [self.collectionView.gifHeader beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
